package net.jueb.frameWorkDemo.mvc4mod.controler.upload;

import java.io.File;
import java.util.concurrent.Callable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.WebAsyncTask;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import net.jueb.frameWorkDemo.mvc4mod.bean.JsonResult;
import net.jueb.frameWorkDemo.mvc4mod.controler.AbstractBaseController;
import net.jueb.util4j.bytesStream.InputStreamUtils;

@Controller
@RequestMapping("/upload")
public class UploadController extends AbstractBaseController{

	
	@RequestMapping(value="/toFileUpload")
	public String toFileUpload()
	{
		return "uploadFiles";
	}
	
	/**
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/uploadFileData",method={RequestMethod.POST})
	@ResponseBody
	public WebAsyncTask<JsonResult> uploadFileData(HttpServletRequest request)
	{
		return buildTask(new Callable<JsonResult>() {

			@Override
			public JsonResult call() throws Exception {
				long time=System.currentTimeMillis();  
				byte[] data=InputStreamUtils.getBytes(request.getInputStream());
				String md5=DigestUtils.md5Hex(data);
				String path=getUploadTempPath(request);
		    	String filePath=path+File.separator+md5;
		    	File saveFile=new File(filePath);
		    	FileUtils.writeByteArrayToFile(saveFile, data);
		    	System.out.println("uploadFileData上传文件:"+md5+",耗时:"+(System.currentTimeMillis() - time)); 
		    	return new JsonResult(0,"success");
			}
		});
	}
	
	/**
	 * 上传文件 用@RequestParam注解来指定表单上的file为MultipartFile
	 * @param file
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/uploadFile")
	@ResponseBody
	public WebAsyncTask<JsonResult> uploadFile(@RequestParam(value = "file") MultipartFile file,HttpServletRequest request)
	{
		return buildTask(new Callable<JsonResult>() {

			@Override
			public JsonResult call() throws Exception {
				if(file.isEmpty())
		    	 {
					return new JsonResult(0,"file.isEmpty");
		    	 }
		    	 long time=System.currentTimeMillis();  
		    	 String fileName=file.getOriginalFilename();
		    	 if(StringUtils.isEmpty(fileName))
		    	 {
		    		 fileName=RandomUtils.nextLong()+"";
		    	 }
		    	 String path=getUploadTempPath(request);
		    	 String filePath=path+File.separator+fileName;
		    	 File saveFile=new File(filePath);
		    	 if(!saveFile.exists()) 
			     {
		    		 saveFile.mkdirs();
			     }
		    	 try {
					file.transferTo(saveFile);
		    	 } catch (Exception e) {
					log.error(e.getMessage(),e);
		    	 }
		    	 System.out.println("uploadFile上传文件:"+fileName+",耗时:"+(System.currentTimeMillis() - time)); 
		    	 return new JsonResult(0,"success");
			}
		});
	}
	
	/**
	 * @param files
	 * @param request
	 * @return
	 */
	@RequestMapping("/uploadFiles")  
	@ResponseBody
	public WebAsyncTask<JsonResult> uploadFiles(@RequestParam("file") MultipartFile[] files,HttpServletRequest request)
	{  
	    return buildTask(new Callable<JsonResult>() {
			@Override
			public JsonResult call() throws Exception {
				for(MultipartFile file:files)
		        {  
		        	if(file.isEmpty())
		        	{
		        		continue;
		        	}
		        	 long time=System.currentTimeMillis();  
		        	 String fileName=file.getOriginalFilename();
		        	 if(StringUtils.isEmpty(fileName))
		        	 {
		        		 fileName=RandomUtils.nextLong()+"";
		        	 }
		        	 String path=getUploadTempPath(request);
		        	 String filePath=path+File.separator+fileName;
		        	 File saveFile=new File(filePath);
		        	 if(!saveFile.exists()) 
				     {
			    		 saveFile.mkdirs();
				     }
		        	 try {
						file.transferTo(saveFile);
		        	 } catch (Exception e) {
						log.error(e.getMessage(),e);
		        	 }
		        	 System.out.println("uploadFiles上传文件:"+fileName+",耗时:"+(System.currentTimeMillis() - time));   
		        }
				return new JsonResult(0,"success");
			}
		}); 
	}

	/**
	 * @param request
	 * @param response
	 * @return
	 */
    @ResponseBody
    public WebAsyncTask<JsonResult> uploadFiles2(HttpServletRequest request,HttpServletResponse response)
    {   
    	 return buildTask(new Callable<JsonResult>() {
 			@Override
 			public JsonResult call() throws Exception {
 				 //创建一个通用的多部分解析器  
 		        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
 		        //判断 request 是否有文件上传,即多部分请求  
 		        if(multipartResolver.isMultipart(request))
 		        {  
 		            //转换成多部分request    
 		            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
 		            for(MultipartFile file:multiRequest.getFileMap().values())
 		            {
 		            	 if(file.isEmpty())
 		            	 {
 		            		continue;
 		            	 }
 		            	 long time=System.currentTimeMillis();  
 		            	 String fileName=file.getOriginalFilename();
 		            	 if(StringUtils.isEmpty(fileName))
 		            	 {
 		            		 fileName=RandomUtils.nextLong()+"";
 		            	 }
 		            	 String path=getUploadTempPath(request);
 		            	 String filePath=path+File.separator+fileName;
 		            	 File saveFile=new File(filePath);
 		            	 if(!saveFile.exists()) 
 					     {
 				    		 saveFile.mkdirs();
 					     }
 		            	 try {
 		            		 
 		    				file.transferTo(saveFile);
 		            	 } catch (Exception e) {
 		    				log.error(e.getMessage(),e);
 		            	 }
 		            	 System.out.println("uploadFiles2上传文件:"+fileName+",耗时:"+(System.currentTimeMillis() - time));   
 		            }
 		        }  
 				return new JsonResult(0,"success");
 			}
 		}); 
    }

	protected String getUploadTempPath(HttpServletRequest request) {
		return null;
	} 
}
